﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using log4net;
using CashFlow.Db.Entity;
using CashFlow.Db.DAL;
using SysAdmin._03_Service._00_Db;
using SysAdmin._04_Form._00_Common;

namespace SysAdmin._04_Form._02_User
{
    public partial class UserStructureForm : Form
    {
        private static ILog _logger = LogManager.GetLogger(typeof(UserStructureForm));
        private IList<UserInfoEntity> AllUsers { get; set; } = new List<UserInfoEntity>();

        public UserStructureForm()
        {
            InitializeComponent();
        }

        private void UserStructureForm_Load(object sender, EventArgs e)
        {

        }

        private void UserStructureForm_Shown(object sender, EventArgs e)
        {
            try
            {
                var ls = UserService.QueryAllUsers();
                AllUsers = ls.Select(x => x.UserInfo).ToList();
                InitTreeView();
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                UICommonTool.ShowAlertDialog(ex.Message);
            }
        }

        private void InitTreeView()
        {
            var ui = AllUsers.Where(x => x.Name == "李茂全").First();
            var rootNode = new TreeNode(ui.Name);
            rootNode.Tag = ui;
            Queue<string> queue = new Queue<string>();
            queue.Enqueue(ui.InvitationCode);
            UserInfoEntity parentUserInfo = ui;
            List<TreeNode> parentNodes = new List<TreeNode>();
            parentNodes.Add(rootNode);
            var tmpParentNodes = new List<TreeNode>();
            int index = 0;
            while (queue.Count > 0)
            {
                string invitationCode = queue.Dequeue();
                var ls = AllUsers.Where(x => x.ReferenceInvitationCode == invitationCode).ToList();

                foreach (var item in ls)
                {
                    var node = new TreeNode(item.Name);
                    node.Tag = item;
                    node.ToolTipText = string.Format("{0} - {1}", item.Name, item.Phone);
                    parentNodes[index].Nodes.Add(node);
                    queue.Enqueue(item.InvitationCode);
                    tmpParentNodes.Add(node);
                }

                index++;
                if (index == parentNodes.Count)
                {
                    parentNodes.Clear();
                    parentNodes.AddRange(tmpParentNodes.ToArray());
                    tmpParentNodes.Clear();
                    index = 0;
                }
            }

            treeView1.BeginUpdate();
            treeView1.Nodes.Add(rootNode);
            treeView1.EndUpdate();
        }
    }
}
